"""
数据库配置文件
将数据库连接参数集中管理，便于维护和测试
"""

import os
from dataclasses import dataclass


@dataclass
class DatabaseConfig:
    """数据库配置类"""
    engine: str = "sql_server.pyodbc"
    name: str = "master"
    host: str = "localhost"
    port: str = "1145"
    user: str = "sa"
    password: str = "shaoyansa"
    driver: str = "ODBC Driver 17 for SQL Server"
    timeout: int = 30
    encrypt: bool = False
    trust_server_certificate: bool = True
    
    @property
    def connection_string(self) -> str:
        """生成ODBC连接字符串"""
        return (
            f"DRIVER={{{self.driver}}};"
            f"SERVER={self.host},{self.port};"
            f"DATABASE={self.name};"
            f"UID={self.user};"
            f"PWD={self.password};"
            f"Encrypt={'yes' if self.encrypt else 'no'};"
            f"TrustServerCertificate={'yes' if self.trust_server_certificate else 'no'};"
            f"Connection Timeout={self.timeout}"
        )
    
    @property
    def django_config(self) -> dict:
        """生成Django数据库配置字典"""
        return {
            'ENGINE': self.engine,
            'NAME': self.name,
            'HOST': self.host,
            'PORT': self.port,
            'USER': self.user,
            'PASSWORD': self.password,
            'OPTIONS': {
                'driver': self.driver,
                'extra_params': f"Encrypt={'yes' if self.encrypt else 'no'};"
                               f"TrustServerCertificate={'yes' if self.trust_server_certificate else 'no'}"
            }
        }


def load_config_from_env() -> DatabaseConfig:
    """从环境变量加载配置"""
    return DatabaseConfig(
        name=os.getenv('DB_NAME', 'management_db'),
        host=os.getenv('DB_HOST', 'localhost'),
        port=os.getenv('DB_PORT', '1433'),
        user=os.getenv('DB_USER', 'management_user'),
        password=os.getenv('DB_PASSWORD', 'StrongPassword123!'),
        driver=os.getenv('DB_DRIVER', 'ODBC Driver 17 for SQL Server'),
        timeout=int(os.getenv('DB_TIMEOUT', '30')),
        encrypt=os.getenv('DB_ENCRYPT', 'yes').lower() == 'yes',
        trust_server_certificate=os.getenv('DB_TRUST_CERT', 'no').lower() == 'yes'
    )


# 默认配置实例
default_config = DatabaseConfig()


if __name__ == "__main__":
    # 测试配置
    config = DatabaseConfig()
    print("连接字符串:", config.connection_string)
    print("Django配置:", config.django_config)